<?php
namespace app\admin\controller;
use think\exception\ValidateException;
use think\facade\Db;
use app\admin\model\Role as RoleModel;

class Login extends Admin{
	
	
	
	//用户登录 
    public function index(){
		if(!$this->request->isPost()) {
			return view('index');
		}else{
			$postField = 'username,password,verify,key';
			$data = $this->request->only(explode(',',$postField),'post',null);
			
			$this->validate($data,\app\admin\validate\Login::class);
			
			//Lee修改start
			$result = $this->checkLogin($data);
			return json($result);
			//Lee修改end
		}
    }

    //验证登录
    private function checkLogin($data){	
		$where['a.user'] = trim($data['username']);
		$where['a.pwd']  = md5(trim($data['password']).config('my.password_secrect'));
		
		$info = Db::name('admin_user')->alias('a')->join('role b', 'a.role_id in(b.role_id)')->field('a.user_id,a.name,a.user as username,a.status,a.role_id as user_role_ids,b.role_id,b.name as role_name,b.status as role_status,b.access')->where($where)->find();
		
		if(!$info){
			throw new ValidateException("请检查用户名或者密码");
		}
		if(!($info['status']) || !($info['role_status'])){
			throw new ValidateException("该账户被禁用");
		}
		
		$info['access'] = explode(',',$info['access']);
    
		
		//登录授权，除开admin和总管账户的限制授权,其他账户都要求授权
		$last_login_ips = Db::name('admin_user')->whereIn('role_id', [1,57])->column('last_login_ip');    //Lee新增
		$last_login_ips = array_filter($last_login_ips, 'strlen');    //Lee新增
		if(!in_array($info['role_id'],[1,57]) && !in_array($_SERVER['REMOTE_ADDR'],$last_login_ips)){    //Lee修改
    		$loginPower['username'] = $data['username'];
			$loginPower['token'] = md5('username'.'cd'.date('YmdHis'));  //Lee新增
    		$loginPower['add_time'] = time();
    		$loginPower['ip'] = $_SERVER['REMOTE_ADDR'];
    		
    		Db::name('login_power')->insertGetId($loginPower);
			return ['status'=>201,'token' => $loginPower['token']];//Lee新增
		}

		Db::name('admin_user')->where('user', $data['username'])->update(['last_login_ip' => $_SERVER['REMOTE_ADDR']]);//Lee新增
		
		session('admin', $info);
		session('admin_sign', data_auth_sign($info));
        
		event('LoginLog',$data['username']);	//写入登录日志
		
        return ['status'=>200];//Lee修改
    }

	//Lee新增start
	public function check(){
		if($this->request->isPost()) {
			$postField = 'token';
			$data = $this->request->only(explode(',',$postField),'post',null);
			if(empty($data['token'])){
				throw new ValidateException("token参数不存在");
			}
			$loginPowerInfo = Db::name('login_power')->where('token', $data['token'])->find();
			if(empty($loginPowerInfo)){
				throw new ValidateException("token信息不存在");
			}
			if($loginPowerInfo['status'] == 0){
				if(  time() > ($loginPowerInfo['add_time'] + 5 * 60)  ){
					return ['status'=>203];    //已过期
				}else{
					return ['status'=>201];    //待授权
				}
			}elseif($loginPowerInfo['status'] == 2){
				return ['status'=>202];    //授权驳回
			}else{
				$info = Db::name('admin_user')->alias('a')->join('role b', 'a.role_id in(b.role_id)')->field('a.user_id,a.name,a.user as username,a.status,a.role_id as user_role_ids,b.role_id,b.name as role_name,b.status as role_status,b.access')->where(['a.user' => $loginPowerInfo['username']])->find();
				$info['access'] = explode(',',$info['access']);
				session('admin', $info);
				session('admin_sign', data_auth_sign($info));
				
				event('LoginLog',$loginPowerInfo['username']);	//写入登录日志
				return ['status'=>200];
			}
		}
	}
	//Lee新增end
	
	
	//验证码
	public function verify(){
		$data['data'] = captcha();
		$data['verify_status'] = config('my.verify_status',true);	//验证码开关
		$data['status'] = 200;
	    return json($data);
	}
	

	//退出
    public function logout(){
        Db::name('admin_user')->where('user', session('admin.username'))->update(['last_login_ip' => '']);
        session('admin', null);
		session('admin_sign', null);
	    return json(['status'=>200]);
    }
	
	
	//阿里云oss上传异步回调返回上传路径，放到这是因为这个地址必须外部能直接访问到
	function aliOssCallBack(){
		$body = file_get_contents('php://input');
		header("Content-Type: application/json");
		$url = $this->getendpoint(config('my.ali_oss_endpoint')).'/'.str_replace('%2F','/',$body);
        return json(['code'=>1,'data'=>$url]);
	}
	
	
	//获取阿里云oss客户端上传地址
	private function getendpoint($str){
		if(strpos(config('my.ali_oss_endpoint'),'aliyuncs.com') !== false){
			if(strpos($str,'https') !== false){
				$point = 'https://'.config('my.ali_oss_bucket').'.'.substr($str,8);
			}else{
				$point = 'http://'.config('my.ali_oss_bucket').'.'.substr($str,7);
			}	
		}else{
			$point = config('my.ali_oss_endpoint');
		}
		return $point;
	}
	

}
